<?php

namespace Modules\Api\Service;

use HiCommon\Repository\CouponGrantDetailRepository;
use HiCommon\Repository\OrderMallRepository;
use HiCommon\Repository\OrderRepairstoreRepository;
use HiCommon\Repository\StoreCarRepository;
use HiCommon\Repository\StoreOrderRepository;
use HiCommon\Repository\StoreOrderGoodsRepository;
use HiCommon\Repository\ShopRepository;
use HiCommon\Repository\GoodsRepository;
use HiCommon\Repository\GoodsProductRepository;
use HiCommon\Repository\StoreOrderRefundRepository;
use HiCommon\Repository\StoreOrderRefundGoodsRepository;
use HiCommon\Service\PublicService;

class StoreOrderService
{
    /**
     * 结算台--预生成订单(详情->立即购买)
     *
     * 2019 11 14
     */
    public function pre_build_order(array $arr_input)
    {
        try {
            if (empty($arr_input['shop_id'])) {
                return hello_error('门店id不能为空');
            }
            if (empty($arr_input['goods_id'])) {
                return hello_error('商品id不能为空');
            }
            if (empty($arr_input['product_id'])) {
                return hello_error('产品id不能为空');
            }
            if (empty($arr_input['goods_num'])) {
                return hello_error('商品数量不能为空');
            }
            if (empty($arr_input['type'])) {
                return hello_error('订单类型不能为空');
            } elseif ($arr_input['type'] == 2 && empty($arr_input['activity_id'])) {
                return hello_error('活动id不能为空');
            }

            $info = self::pre_build($arr_input);//详情
            $total_amount = number_format_money($info['total_price']);

            if ($info['is_free'] == 1) {
                $delivery_price = self::get_shop_delivery_price((int)$arr_input['shop_id'], $total_amount);//运费
            } else {
                $delivery_price = '0.00';
            }
            $address = AddressService::get_defaule_address();

            $res = [
                'info' => [0 => $info],
                'total_amount' => $total_amount,
                'delivery_price' => $delivery_price,
                'default_address' => $address['data'] ? $address['data'] : null
            ];

            return hello_success('成功', $res);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 结算台--预生成订单(购物车进入)
     *
     * 2019 11 14
     */
    public function pre_build_order_by_car(array $arr_input)
    {
        try {
            if (empty($arr_input['car_id'])) {
                return hello_error('数据id不能为空');
            }

            $ids = hi_array_del_null($arr_input['car_id']);
            $data = StoreCarRepository::get_list_by_where_in($ids);//购物车中数据

            if (empty($data)) {
                return hello_error('购物车id不存在');
            }

            $info = [];
            foreach ($data as $key => $value) {
                $map_array = [
                    'car_id' => $value['id'],
                    'type' => $value['type'],
                    'shop_id' => $value['shop_id'],
                    'goods_id' => $value['goods_id'],
                    'product_id' => $value['goods_product_id'],
                    'goods_num' => $value['goods_num'],
                    'activity_id' => $value['activity_id'],
                ];

                $info[] = self::pre_build($map_array);//详情
            }

            $total_amount = number_format_money(array_sum(array_column($info, 'total_price')));

            if (min(array_column($info, 'is_free')) == 1) {
                $delivery_price = self::get_shop_delivery_price((int)$map_array['shop_id'], $total_amount);//运费
            } else {
                $delivery_price = '0.00';
            }

            $address = AddressService::get_defaule_address();
            $res = [
                'info' => $info,
                'total_amount' => $total_amount,
                'delivery_price' => $delivery_price,
                'default_address' => $address['data']
            ];

            return hello_success('成功', $res);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 预生成订单
     *
     * 2019 11 14
     */
    public function pre_build($data)
    {
        $g_field['field'] = ['id', 'name', 'is_free'];
        $goods_obj = GoodsRepository::get_one((int)$data['goods_id'], $g_field);

        $p_field['field'] = ['id', 'goods_id', 'goods_specs_id', 'price', 'stock', 'pic'];
        $p_field['with'] = ['specs'];
        $product_obj = GoodsProductRepository::get_one((int)$data['product_id'], $p_field);

        $info = [];
        if ($goods_obj->first() && $product_obj->first()) {
            $goods = $goods_obj->toArray();
            $product = $product_obj->toArray();

            $total_price = (int)$data['goods_num'] * $product['price'];
            $info = [
                'shop_id' => $data['shop_id'],
                'good_id' => $goods['id'],
                'good_name' => $goods['name'],
                'good_pic' => $product['pic']['full_src'],
                'good_specs' => $product['specs']['name'],
                'good_price' => $product['price'],
                'product_id' => $product['id'],
                'goods_num' => $data['goods_num'],
                'total_price' => number_format_money($total_price),
                'is_free' => $goods['is_free']
            ];

            if ($data['type'] == 2) {
                $cat_id = ['activity_id' => $data['activity_id']];
                $info = array_merge($info, $cat_id);//活动id
            }
        }

        return $info;
    }

    /**
     * 门店运费
     *
     * 2019 11 14
     */
    public function get_shop_delivery_price(int $shop_id, $total_amount)
    {
        $map = ['id' => $shop_id];
        $arr_option['field'] = ['id', 'delivery', 'delivery_price', 'order_price'];
        $delivery = ShopRepository::get_one_by_where($map, $arr_option);
        if ($total_amount >= $delivery->order_price) {
            return '0.00';
        }
        if ($delivery->first() && $delivery->delivery == 1) {
            return $delivery->delivery_price;
        }

        return '0.00';
    }

    /**
     * 订单数据验证
     */
    public function check_arr_input($arrInput)
    {
        if (empty($arrInput['shop_id'])) {
            return ['state' => 1, 'msg' => '门店id不能为空'];
        }
        if (empty($arrInput['order_type'])) {
            return ['state' => 1, 'msg' => '订单类型不能为空'];
        }
        if (empty($arrInput['delivery_price'])) {
            return ['state' => 1, 'msg' => '配送费用不能为空'];
        } else {
            $arrInput['delivery_price'] = (float)$arrInput['delivery_price'];
        }
        if (empty($arrInput['pay_amount'])) {
            return ['state' => 1, 'msg' => '实际支付金额不能为空'];
        } else {
            $arrInput['pay_amount'] = (float)$arrInput['pay_amount'];
        }
        if (empty($arrInput['user_address_id'])) {
            return ['state' => 1, 'msg' => '买家收货地址不能为空'];
        }
        if (empty($arrInput['goods'])) {
            return ['state' => 1, 'msg' => '商品信息不能为空'];
        }
        foreach ($arrInput['goods'] as $key => $value) {
            if (empty($value['id'])) {
                return ['state' => 1, 'msg' => '商品id不能有空'];
            }
            if (empty($value['product_id'])) {
                return ['state' => 1, 'msg' => '产品id不能有空'];
            }
            if (empty($value['goods_num'])) {
                return ['state' => 1, 'msg' => '产品数量不能有空'];
            } else {
                $arrInput['goods_total'] += $value['goods_num'];
            }

            $arr_option['field'] = ['name', 'status'];
            $goods = GoodsRepository::get_one((int)$value['id'], $arr_option);//验证商品是否下架
            if ($goods->first() && $goods->status != 1) {
                return ['state' => 1, 'msg' => $goods->name . '【已下架】'];
            }

            $option['field'] = ['id', 'goods_id', 'price', 'stock', 'pic', 'goods_specs_id'];
            $option['with'] = ['specs'];
            $product = GoodsProductRepository::get_one((int)$value['product_id'], $option); //获取商品价格
            if ($product->first()) {
                if ($product->stock < $value['goods_num']) {
                    return ['state' => 1, 'msg' => $goods->name . '【库存不足】'];
                }

                $arrInput['order_amount'] += (float)$product->price * $value['goods_num'];//订单总额
                $goods_amount = $value['goods_num'] * $product->price;//同一规格产品总额
                $arrInput['order_goods_data'][] = [
                    'goods_product_id' => $value['product_id'],
                    'goods_id' => $product->goods_id,
                    'goods_num' => $value['goods_num'],
                    'goods_price' => (float)$product->price,
                    'goods_amount' => $goods_amount,
                    'goods_name' => $goods->name,
                    'goods_specs' => $product->specs['name'],
                    'goods_pic' => $product->pic['src'],
                ];
            }

        }

        return $arrInput;
    }

    /**
     * 生成订单（订单创建成功后用户端唤起支付）
     *
     * 2019 11 15
     */
    public function create_order(array $arr_input)
    {
        try {
            //对提交的数据进行验证
            $data = self::check_arr_input($arr_input);
            if ($data['state'] == 1) {
                return $data;
            }

            //优惠券或活动---优惠金额计算
            if (!empty($data['coupons_id']) && !empty($data['user_coupons_id']) && $data['order_type'] == 1) {
                $coupons_array = ['type' => 1, 'order_amount' => $data['order_amount'], 'coupon_id' => $data['coupons_id']];
                $coupon = PublicService::order_imputed_price((array)$coupons_array);

                if ($coupon['state'] == 0) {
                    $data['coupon_price'] = $coupon['data']['coupon_price'];

                    //更新优惠券为以使用
                    $up_coupon = ['id' => $data['user_coupons_id'], 'status' => 2, 'repairstore_id' => $data['shop_id']];
                    CouponGrantDetailRepository::edit_one($up_coupon);
                } else {
                    return $coupon;
                }

            } elseif (!empty($data['activity_id']) && $data['order_type'] == 2) {
                $coupons_array = ['type' => 2, 'order_amount' => $data['order_amount'], 'activity_id' => $data['activity_id']];
                $coupon = PublicService::order_imputed_price((array)$coupons_array);

                if ($coupon['state'] == 0) {
                    $data['coupon_price'] = $coupon['data']['coupon_price'];
                } else {
                    return $coupon;
                }

            } else {
                $data['coupon_price'] = 0.00;
            }

            //生成订单
            return self::add_order_info($data);

        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 生成订单数据
     */
    public function add_order_info($data)
    {
        //计算实际应支付金的额
        $payable = $data['order_amount'] - $data['coupon_price'] + $data['delivery_price'];

        if (round($data['pay_amount'], 2) != round($payable, 2)) {
            return hello_error('实际支付金额计算有误,订单创建失败');
        } elseif (round($payable, 2) <= 0.00) {
            return hello_error('实付金额小于0元，订单创建失败');
        }

        $order_data = [
            'order_type' => $data['order_type'],
            'order_no' => random_order_sn('PTSHP'),
            'shop_id' => $data['shop_id'],
            'user_id' => $data['user_id'],
            'activity_id' => $data['activity_id'],
            'goods_num' => $data['goods_total'],
            'order_amount' => $data['order_amount'],
            'coupons_id' => $data['coupons_id'],
            'user_coupons_id' => $data['user_coupons_id'],
            'coupon_price' => $data['coupon_price'],
            'delivery_price' => $data['delivery_price'],
            'user_address_id' => $data['user_address_id'],
            'pay_amount' => $payable,
            'remark' => $data['remark'],
        ];

        $store_order = StoreOrderRepository::add_one($order_data);//主订单表

        $time = date('Y-m-d H:i:s');
        foreach ($data['order_goods_data'] as $key => &$value) {
            $value['store_order_id'] = $store_order->id;
            $value['refund_price'] = $value['goods_amount'] - ($data['coupon_price'] / $data['order_amount'] * $value['goods_amount']);
            /*$value['goods_name'] = $value['goods_name'];
            $value['goods_specs'] = $value['goods_specs'];
            $value['goods_pic'] = $value['goods_pic'];*/
            $value['created_at'] = $time;
            $value['updated_at'] = $time;

            //扣除库存
            GoodsProductRepository::decrease_num($value['goods_product_id'], 'stock', $value['goods_num']);

            //更新商品表售出的数量
            GoodsRepository::increase_num($value['goods_id'], $value['goods_num']);
        }

        //生成订单副表数据
        $store_order_goods = StoreOrderGoodsRepository::add_many($data['order_goods_data']);

        //如果是购物车进来删除购物车记录
        if (!empty($data['car_ids'])) {
            StoreCarRepository::delete_by_where_in($data['car_ids']);
        }

        if ($store_order && $store_order_goods && $payable > 0) {
            $res = [
                'order_id' => $store_order->id,
                'order_no' => $order_data['order_no'],
                'payable' => number_format_money($payable)  //实际应该支付的金额
            ];

            return hello_success('订单创建成功', $res);
        }
        return hello_error('订单创建失败');
    }

    /**
     * 取消订单
     *
     * 2019 11 19
     */
    public function cancel_order(array $arr_input)
    {
        try {
            if (empty($arr_input['order_id'])) {
                return hello_error('订单id不能为空');
            }
            if (empty($arr_input['order_no'])) {
                return hello_error('订单编号不能为空');
            }
            if (empty($arr_input['cancel_reason'])) {
                return hello_error('取消原因不能为空');
            }
            //获取订单信息
            $map = ['id' => $arr_input['order_id'], 'order_no' => $arr_input['order_no'], 'user_id' => $arr_input['user_id']];
            $arr_option['field'] = ['id', 'id', 'status', 'pay_status', 'outer_trade_no', 'pay_type', 'user_coupons_id'];
            $order_obj = StoreOrderRepository::get_one_by_where($map, $arr_option);
            if ($order_obj->first()) {
                $order_array = $order_obj->toArray();//订单详情数组

                if ($order_array['status'] == 1 && $order_array['pay_status'] == 1) { //未支付订单->取消

                    $up_data = [
                        'status' => 5,
                        'order_status' => 5,
                        'cancel_time' => date('Y-m-d H:i:s', time()),
                        //'cancel_reason_id' => $arr_input['cancel_reason_id'],
                        'cancel_reason' => $arr_input['cancel_reason']
                    ];
                    //取消订单
                    StoreOrderRepository::edit_one((array)['id' => $order_array['id']], (array)$up_data);

                    //回收库存,如果有有优惠券将优惠券更新为未使用
                    StoreOrderRepository::cancelOrderBackStock((int)$order_array['id'], $order_array['user_coupons_id']);

                    return hello_success('取消成功');
                } else {
                    return hello_error('该订单状态有误，取消失败');
                }

            } else {
                return hello_error('该订单不存在或无效');
            }

            return hello_error('取消失败');
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 申请退款-申请退货
     *
     * 2019 11 19
     */
    public function refund_order(array $arr_input)
    {
        try {
            if (empty($arr_input['order_id'])) {
                return hello_error('订单id不能为空');
            }
            if (empty($arr_input['order_no'])) {
                return hello_error('订单编号不能为空');
            }
            if (empty($arr_input['cancel_reason_id'])) {
                return hello_error('原因id不能为空');
            }
            //获取订单信息
            $map = ['id' => $arr_input['order_id'], 'order_no' => $arr_input['order_no'], 'user_id' => $arr_input['user_id']];
            $arr_option['field'] = ['id', 'status', 'pay_status', 'outer_trade_no', 'pay_type', 'shop_id', 'delivery_price', 'is_finish'];
            $order_obj = StoreOrderRepository::get_one_by_where($map, $arr_option);
            if ($order_obj->first()) {
                $order_array = $order_obj->toArray();//订单详情数组

                //订单已完成不可申请售后
                if ($order_array['is_finish'] == 1) {
                    return hello_error('该订单已完成！');
                }

                $arr_input['shop_id'] = $order_array['shop_id'];
                if ($order_array['status'] == 1 && $order_array['pay_status'] == 2) {

                    /***********************已支付订单未发货->更改订单状态为 已退款  并直接退款*************************/
                    StoreOrderRepository::change_one_state((int)$order_array['id'], 6);

                    self::add_refund_info($arr_input, $order_array['delivery_price']);

                    return hello_success('申请成功，等待管理员审核-退款');
                } elseif (in_array($order_array['status'], [2, 3, 4]) && $order_array['pay_status'] == 2) {

                    /***********************已支付订单已发货->更改订单状态为申请  退货 并生成退单记录***********************/
                    // StoreOrderRepository::change_one_state((int)$order_array['id'], 8);

                    //生成退单记录
                    self::add_refund_info($arr_input);

                    return hello_success('申请成功，等待管理员审核-退货');
                } else {
                    return hello_error('该订单状态有误，申请失败');
                }

            } else {
                return hello_error('该订单不存在或无效');
            }

            return hello_error('申请失败');
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 生成退单记录
     */
    public function add_refund_info($arr_input, $delivery_price = 0)
    {
        $picture = '';
        if (!empty($arr_input['picture'])) {
            $picture = json_encode($arr_input['picture']);
        }
        $order_goods_id_array = hi_array_del_null($arr_input['order_goods_id']);

        //计算退单金额
        $refund = StoreOrderGoodsRepository::get_by_where_in($order_goods_id_array)->toArray();
        if ($refund) {
            $refund_amount = number_format_money(array_sum(array_column($refund, 'refund_price')));
        } else {
            $refund_amount = 0;
        }
        //生成退单记录
        $refund_array = [
            'user_id' => $arr_input['user_id'],
            'shop_id' => $arr_input['shop_id'],
            'store_order_id' => $arr_input['order_id'],
            'refund_no' => random_order_sn('SALE'),
            'apply_type' => $arr_input['apply_type'],
            'apply_state' => 1,
            'refund_amount' => $refund_amount + $delivery_price,
            'refund_reason_id' => $arr_input['cancel_reason_id'],
            'refund_reason' => $arr_input['refund_reason'],
            'picture' => $picture
        ];

        $order_refund = StoreOrderRefundRepository::add_one($refund_array);

        $refund_goods = [];
        foreach ($order_goods_id_array as $item) {
            $refund_goods[] = [
                'store_order_refund_id' => $order_refund->id,
                'store_order_goods_id' => intval($item)
            ];
        }
        StoreOrderRefundGoodsRepository::add_many($refund_goods);//存入售后退货关系

        if ($order_goods_id_array && $order_refund->id) {
            StoreOrderGoodsRepository::change_by_where_in($order_goods_id_array, ['is_refund' => 1]);//修改为退货
        }

        //消息通知
        $dataNotice = [
            'notice_type' => 'ptshp_sales_message_push',
            'refund_order_id' => $order_refund->id,
            'type' => 31,
            'title' => '售后申请通知',
            'content' => '申请成功，等待管理员审核。'
        ];
        predis_notice_queue_in($dataNotice);
    }

    /**
     * 获取用户订单列表
     *
     * 2019 11 20
     */
    public function get_order_list(array $arr_input)
    {
        try {
            //$arr_where['or'] = ['1', '2', '3', '4', '5'];
            $arr_where['user_id'] = (int)$arr_input['user_id'];
            $status = (int)$arr_input['status'];
            if (!empty($status)) {
                if ($status == 1) { //待支付
                    $arr_where['status'] = 1;
                    $arr_where['pay_status'] = 1;
                } elseif ($status == 2) {//待发货
                    $arr_where['status'] = 1;
                    $arr_where['pay_status'] = 2;
                } elseif ($status == 3) {//待收货
                    $arr_where['status'] = 2;
                } elseif ($status == 4) {//待评价
                    $arr_where['status'] = 3;
                }
            }

            $arr_option['with'] = ['getOrderGoods', 'shop_name'];
            $arr_option['field'] = ['id', 'shop_id', 'order_type', 'order_no', 'status', 'pay_status', 'goods_num',
                'pay_amount', 'created_at', 'delivery_price', 'order_amount', 'coupon_price', 'is_finish'];
            $arr_list = StoreOrderRepository::get_list_by_where($arr_where, $arr_option);
            $list = list_page_data($arr_list);
            $order['list'] = [];
            foreach ($list['data'] as $key => $value) {
                $goods = [];
                foreach ($value['get_order_goods'] as $ky => $val) {
                    $goods[] = [
                        'goods_id' => $val['goods_id'],
                        'order_goods_id' => $val['id'],
                        'goods_price' => $val['goods_price'],
                        'goods_num' => $val['goods_num'],
                        'goods_name' => $val['goods_name'],
                        'goods_pic' => $val['goods_pic']['full_src'],
                        'goods_specs' => $val['goods_specs'],
                        'refund_price' => $val['refund_price'],
                        'is_refund' => $val['is_refund'],
                        'refund_status' => self::goods_refund_status($val['goods_refund_status']['order_refund']),
                    ];
                }

                $order['list'][] = [
                    'shop_id' => $value['shop_id'],
                    'shop_name' => $value['shop_name']['name'],
                    'order_id' => $value['id'],
                    'order_type' => $value['order_type'],
                    'order_no' => $value['order_no'],
                    'order_amount' => $value['order_amount'],
                    'delivery_price' => $value['delivery_price'],
                    'coupon_price' => $value['coupon_price'],
                    'status' => $value['status'],
                    'pay_status' => $value['pay_status'],
                    'goods_total' => $value['goods_num'],
                    'need_pay_amount' => $value['pay_amount'],
                    'created_at' => $value['created_at'],
                    'is_finish' => $value['is_finish'],
                    'order_goods' => $goods,
                ];
            }

            $order['page'] = $list['page_data'];

            return hello_success('获取成功！', $order);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }


    /**
     * 商品退单状态
     */
    public function goods_refund_status($data)
    {
        if (!empty($data)) {
            $type = $data['apply_type'] == 1 ? '款' : '货';
            if ($data['apply_state'] == 1) {
                return '申请退' . $type;
            } elseif ($data['apply_state'] == 2) {
                return '申请通过';
            } elseif ($data['apply_state'] == 3) {
                return '被驳回';
            } elseif ($data['apply_state'] == 4) {
                return '已退款';
            }
        }

        return '';
    }

    /**
     * 获取订单详情
     *
     * 2019 11 20
     */
    public function get_order_info(array $arr_input)
    {
        try {
            $order_id = (int)$arr_input['order_id'];
            if (empty($order_id)) {
                return hello_error('订单id不能为空！');
            }
            $arr_option['with'] = ['getOrderGoods', 'getAddress', 'getExpress', 'shop_name'];
            $arr_list = StoreOrderRepository::get_one($order_id, $arr_option);

            if ($arr_list->first()) {
                $order = $arr_list->toArray();
                foreach ($order['get_order_goods'] as $key => $value) {
                    $goods[] = [
                        'goods_id' => $value['goods_id'],
                        'order_goods_id' => $value['id'],
                        'goods_name' => $value['goods_name'],
                        'goods_price' => $value['goods_price'],
                        'goods_num' => $value['goods_num'],
                        'refund_price' => $value['refund_price'],
                        'goods_specs' => $value['goods_specs'],
                        'goods_pic' => $value['goods_pic']['full_src'],
                        'is_refund' => $value['is_refund'],
                        'refund_status' => self::goods_refund_status($value['goods_refund_status']['order_refund']),
                    ];
                }
                $order['get_order_goods'] = $goods;
                $order['order_status'] = StoreOrderRepository::order_status($order['status'], $value['pay_status']);

                return hello_success('获取成功！', $order);
            }
            return hello_error('订单不存在');

        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 删除订单
     *
     * 2019 11 21
     */
    public function del_order(array $arr_input)
    {
        try {
            $order_id = (int)$arr_input['order_id'];
            if (empty($order_id)) {
                return hello_error('订单id不能为空！');
            }
            if (StoreOrderRepository::delete_one($order_id)) {
                return hello_success('删除成功！');
            }
            return hello_error('删除失败！');
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 确认收货
     *
     * 2019 11 21
     */
    public function confirm_receipt(array $arr_input)
    {
        try {
            $order_id = (int)$arr_input['order_id'];
            if (empty($order_id)) {
                return hello_error('订单id不能为空！');
            }

            $map = ['id' => $order_id, 'user_id' => $arr_input['user_id']];
            $up_data = ['status' => 3, 'order_status' => 3, 'receive_time' => date('Y-m-d H:i:s')];
            if (StoreOrderRepository::edit_one($map, $up_data)) {
                //消息通知
                $dataNotice = [
                    'notice_type' => 'ptshp_order_message_push',
                    'order_id' => $order_id,
                    'type' => 31,
                    'title' => '收货通知',
                    'content' => '已签收。'
                ];
                predis_notice_queue_in($dataNotice);

                return hello_success('成功！');
            }
            return hello_error('失败！');
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 统计各类进行中的订单数量
     */
    public function count_order_num($user_id)
    {
        $where = ['user_id' => $user_id];
        //普通订单
        $general = StoreOrderRepository::count_order($where);

        //积分订单
        $integral = OrderMallRepository::count_order($where);

        //服务保养订单
        $repair = OrderRepairstoreRepository::count_order($where);

        //售后（普通）
        $sale_general = StoreOrderRepository::count_sale_order($where);

        //售后（服务保养）
        $sale_repair = OrderRepairstoreRepository::count_sale_order($where);

        $res = [
            'general' => $general,            //普通订单
            'integral' => $integral,          //积分订单
            'repair' => $repair,              //服务保养订单
            'sale_general' => $sale_general,  //售后（普通）
            'sale_repair' => $sale_repair,    //售后（服务保养）
        ];

        return $res;
    }

    /**
     * 获取售后订单列表
     */
    public function get_sale_order(array $arr_input)
    {
        try {
            $arr_option['where'] = ['user_id' => $arr_input['user_id']];
            $arr_option['with'] = ['shop_name', 'store_order', 'get_order_refund_goods', 'refund_reason_id'];
            $list_obj = StoreOrderRefundRepository::get_list($arr_option);
            $list = list_page_data($list_obj);

            $order['list'] = [];
            foreach ($list['data'] as $key => $value) {
                if ($value['apply_state'] == 2 && $value['apply_type'] == 3 && empty($value['express_id'])) {
                    $express = true;
                } else {
                    $express = false;
                }

                $status = [1 => '退款', 2 => '退款', 3 => '退货退款'];

                $order['list'][] = [
                    'refund_id' => $value['id'],
                    'shop_id' => $value['shop_name']['id'],
                    'shop_name' => $value['shop_name']['name'],
                    'order_id' => $value['store_order']['id'],
                    'order_type' => $value['store_order']['order_type'],
                    'order_no' => $value['store_order']['order_no'],
                    'refund_no' => $value['refund_no'],
                    'created_at' => $value['store_order']['created_at'],
                    'goods_total' => $value['store_order']['goods_num'],
                    'status' => $value['store_order']['status'],
                    'order_amount' => $value['store_order']['order_amount'],
                    'coupon_price' => $value['store_order']['coupon_price'],
                    'pay_amount' => $value['store_order']['pay_amount'],
                    'refund_total_price' => $value['refund_amount'],
                    //'order_status' => $value['apply_type'] == 1 ? '退款' : '退货',
                    'order_status' => $status[$value['apply_type']] ?? '错误单',
                    'is_logistics' => empty($value['express_id']) ? false : true,
                    'express' => $express,
                    'order_goods' => self::goods_data_action($value['get_order_refund_goods'], $value['apply_state']),
                ];
            }

            $order['page'] = $list['page_data'];

            return hello_success('获取成功！', $order);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 商品数据整理
     */
    public function goods_data_action($order_goods, $apply_state)
    {
        $goods = [];
        foreach ($order_goods as $ky => $value) {
            $val = $value['order_goods'];
            $refund_status = '';
            if ($apply_state == 1) {
                $refund_status = '申请中';
            } elseif ($apply_state == 2) {
                $refund_status = '申请通过';
            } elseif ($apply_state == 3) {
                $refund_status = '被驳回';
            } elseif ($apply_state == 4) {
                $refund_status = '已退款';
            }
            $goods[] = [
                'goods_id' => $val['goods_id'],
                'goods_price' => $val['goods_price'],
                'goods_num' => $val['goods_num'],
                'goods_name' => $val['goods_name'],
                'goods_pic' => $val['goods_pic']['full_src'],
                'goods_specs' => $val['goods_specs'],
                'is_refund' => $val['is_refund'],
                'refund_price' => $val['refund_price'],
                'refund_status' => $refund_status
            ];
        }

        return $goods;
    }

    /**
     * 获取售后单详情
     *
     * 2020-02-27
     */
    public function get_sale_order_info(array $arr_input)
    {
        try {
            $refund_id = (int)$arr_input['refund_id'];
            if (empty($refund_id)) {
                return hello_error('退单id不能为空！');
            }
            $arr_option['with'] = ['get_order_refund_goods', 'shop_name', 'store_order', 'refund_reason_id'];
            $arr_list = StoreOrderRefundRepository::get_one($refund_id, $arr_option);


            if ($arr_list->first()) {
                $order = $arr_list->toArray();

                if ($order['apply_state'] == 2 && empty($order['express_id'])) {
                    $refund_data['express'] = true;
                } else {
                    $refund_data['express'] = false;
                }
                $refund_data['refund_id'] = $order['id'];
                $refund_data['is_logistics'] = empty($order['express_id']) ? false : true;//是否有物流信息
                $refund_data['apply_state'] = $order['apply_state'];
                $refund_data['apply_type'] = $order['apply_type'] == 1 ? '退款' : '退货';
                $refund_data['pay_type'] = $order['store_order']['pay_type'];
                $refund_data['refund_no'] = $order['refund_no'];
                $refund_data['created_at'] = $order['created_at'];
                $refund_data['refund_total_price'] = $order['refund_amount'];

                $refund_data['shop'] = $order['shop_name'];
                $refund_data['order_goods'] = self::goods_data_action($order['get_order_refund_goods'], $order['apply_state']);
                //退款退货信息
                $picture_arr = [];
                if (!empty($order['picture'])) {
                    $picture = json_decode($order['picture']);
                    foreach ($picture as $key => $value) {
                        $picture_arr[] = oss_full_url($value);
                    }
                }
                $refund_data['order_refund'] = [
                    'reason' => $order['refund_reason'],
                    'reason_tag' => $order['refund_reason_id']['reason'],
                    'created_at' => $order['created_at'],
                    'deal_at' => $order['deal_at'],
                    'picture' => $picture_arr
                ];

                return hello_success('获取成功！', $refund_data);
            }

            return hello_error('订单不存在');
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 创建退货物流信息
     */
    public function refund_order_express(array $arr_input)
    {
        try {
            $refund_id = intval($arr_input['refund_id']);
            $express_id = intval($arr_input['express_id']);
            if (empty($refund_id)) {
                return hello_error('退单id不能为空！');
            }
            if (empty($express_id)) {
                return hello_error('快递id不能为空！');
            }
            if (empty($arr_input['express_no'])) {
                return hello_error('单号不能为空！');
            }
            if (empty($arr_input['express_pic'])) {
                return hello_error('邮寄凭证不能为空！');
            }

            if (!empty($arr_input['express_pic'])) {
                $picture = json_encode($arr_input['express_pic']);
            }

            $express_ary = [
                'id' => $refund_id,
                'express_id' => $express_id,
                'express_no' => $arr_input['express_no'],
                'express_pic' => $picture ?? '',
            ];

            StoreOrderRefundRepository::edit_one($express_ary);

            return hello_success('提交成功！');
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }

    }

    /**
     * 支付-检查订单
     */
    public function check_pay_order_api($n_id, $n_uid)
    {
        try {
            if ($n_id <= 0) {
                return hello_error('数据id不能为空');
            }
            if ($n_uid <= 0) {
                return hello_error('用户id不能为空');
            }

            //查询订单信息
            $map = ['id' => $n_id, 'user_id' => $n_uid, 'pay_status' => 1, 'status' => 1];
            $order_obj = StoreOrderRepository::get_one_by_where($map);

            if ($order_obj->first()) {
                $order_array = $order_obj->toArray();//订单详情数组
                $arr_data = [
                    'out_trade_no' => $order_array['order_no'],
                    'total_fee' => $order_array['pay_amount'] * 100// **单位：分**
                ];

                return hello_success('成功', $arr_data);
            }

            return hello_error('该订单不存在或无效，请重新下单');
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /**
     * 支付回调-订单处理
     */
    public function notify_for_ptshp($s_order_sn = '', $s_transaction_id = '', $s_pay_time = null)
    {
        //订单状态修改
        $arr_where = ['order_no' => $s_order_sn];
        $arr_data = [
            'pay_status' => 2,
            'pay_type' => 2,
            'outer_trade_no' => $s_transaction_id,
            'pay_time' => $s_pay_time,
        ];
        $res = StoreOrderRepository::edit_one($arr_where, $arr_data);

        if ($res === false) {
            return hello_error('确认失败', [], '订单状态修改失败');
        }

        return hello_success('成功');
    }

    /**
     * 支付完成后-查询订单
     */
    public function order_result_for_ptshp($n_id)
    {
        try {
            if ($n_id <= 0) {
                return hello_error('数据id不能为空');
            }
            $arr_option = [
                'field' => ['id', 'pay_status']
            ];
            $result = StoreOrderRepository::get_one_by_where(['id' => $n_id], $arr_option);
            if (is_null($result)) {
                return hello_error('数据不存在');
            }
            $result = [
                'id' => $result->id,
                'pay_state' => $result->pay_status,
            ];


            return hello_success('成功', $result);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

}